<template>
  <div class="chat_box">
    <header>我是蓝天</header>
    <div class="msg_box" ref="msg_box">
      <div v-for="(item,index) in list" :key="index" class="msg" 
           :style="item.userId == userId? 'flex-direction:row-reverse' : ''">
        <div class="user-head" v-if="userId">
          <div class="head"></div>
        </div>
        <div class="user_msg" v-if="userId">
          <span :style="item.userId == userId ? 'float: right;' : ''" :class="item.userId == userId ? 'right' : 'left'">
            {{item.content}}
          </span>
        </div>
      </div>
    </div>
    <div class="input_box">
      <input type="text" ref="sendMsg" v-model="contentText" @keyup.enter="sendText()"/>
      <div class="btn" @click="sendText()">发送</div>
    </div>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      ws: null,

      count: 0,

      //当前用户ID
      userId: 0,

      //聊天记录的数组
      list: [],

      //input输入的值
      contentText: ""
    };
  },
  created() {
    
  },
  mounted(){
    this.initWebSocket();
  },
  methods: {
    //进入页面创建websocket连接
    initWebSocket() {
      let _this = this

      //判断页面有没有存在websocket连接
      if(window.WebSocket){
        let ws = new WebSocket("ws://localhost:3000")
        this.ws = ws

        ws.onopen = function(){
          console.log("服务器连接成功")
        }

        ws.onclose = function(){
          console.log("服务器连接关闭")
        }

        ws.onerror = function(){
          console.log("服务器连接出错")
        }

        ws.onmessage = function(e) {
          _this.checkStatus()

          //接收服务器返回的数据
          let resData = JSON.parse(e.data)
          
          if(resData.funName == "userCount") {
            _this.count = resData.users;
            _this.list = resData.chat;
          }else{
            _this.list.push({
              userId: resData.userId, content: resData.msg
            })
          }
        }
      }
    },
    
    //发送聊天信息
    sendText() {
      let _this = this

      // 发送完信息之后失去焦点
      this.$refs["sendMsg"].focus()

      // 判断如果输入位空，则不向服务器发送数据
      if(!this.contentText){
        return
      }
      let params = {
        userId: this.userId,
        msg: this.contentText
      }
      //调用WebSocket send()发送信息的方法
      this.ws.send(JSON.stringify(params))
      this.contentText = ""

      setTimeout(() => {
        _this.scrollBottm()
      }, 500)
    },

    //滚动条到底部
    scrollBottm() {
      let el = this.$refs["msg_box"];
      el.scrollTop = el.scrollHeight;
    },

    // 当客户端想发送消息是，判断其是否登陆
    checkStatus(){
      // 检查用户名是否为空
      var status = sessionStorage.getItem("token")
      if(status){
        this.userId = JSON.parse(status)
      }

      while(!status){
        var person = prompt("请输入您的用户名")
        if(person != null){
          sessionStorage.setItem("token", JSON.stringify(person))
          this.userId = person
        }

        status = sessionStorage.getItem("token")
      }
    }
  }
};
</script>
 
<style>
.chat_box {
  margin: 0 auto;
  background: #fafafa;
  position: absolute;
  height: 100%;
  width: 100%;
}

.chat_box header{
  position: fixed;
  width: 100%;
  height: 3rem;
  background: #409eff;
  max-width: 700px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
  color: white;
  font-size: 1rem;
  z-index: 999;
}

.chat_box .msg_box{
  position: absolute;
  height: 100%;
  width: 100%;
  overflow-y: scroll;
  box-sizing: border-box;
  padding: 3rem 0;
}
.chat_box .msg_box .msg{
  width: 95%;
  min-height: 2.5rem;
  margin: 1rem 0.5rem;
  position: relative;
  display: flex;
  justify-content: flex-start !important;
}
.chat_box .msg_box .msg .user-head{
  min-width: 2.5rem;
  width: 20%;
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
  background: #f1f1f1;
  display: flex;
  justify-content: center;
  align-items: center;
}
.chat_box .msg_box .msg .user-head .head{
  width: 1.2rem;
  height: 1.2rem;
}

.chat_box .msg_box .msg .user_msg{
  width: 80%;
  word-break: break-all;
  position: relative;
  z-index: 5;
}
.chat_box .msg_box .msg .user_msg span{
  display: inline-block;
  padding: 0.5rem 0.7rem;
  border-radius: 0.5rem;
  margin-top: 0.2rem;
  font-size: 0.88rem;
}
.chat_box .msg_box .msg .user_msg .left{
  background: white;
  animation: toLeft 0.5s ease both 1;
}
.chat_box .msg_box .msg .user_msg .right{
  background: #53a8ff;
  color: white;
  animation: toright 0.5s ease both 1;
}
@keyframes toLeft {
  0% {
    opacity: 0;
    transform: translateX(-10px);
  }
  100% {
    opacity: 1;
    transform: translateX(0px);
  }
}
@keyframes toright {
  0% {
    opacity: 0;
    transform: translateX(10px);
  }
  100% {
    opacity: 1;
    transform: translateX(0px);
  }
}

.chat_box .input_box{
  padding: 0 0.5rem;
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 1.5rem;
  background: #fafafa;
  box-shadow: 0 0 5px #ccc;
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 999;
}

.chat_box .input_box input{
  height: 1.3rem;
  display: inline-block;
  width: 100%;
  border: none;
  border-radius: 0.2rem;
  font-size: 0.88rem;
}
.chat_box .input_box .btn{
  height: 1.3rem;
  min-width: 4rem;
  background: #e0e0e0;
  font-size: 0.88rem;
  color: white;
  text-align: center;
  border-radius: 0.2rem;
  margin-left: 0.5rem;
  transition: 0.5s;
}
.chat_box .input_box input .btn_active{
  background: #409eff;
}
</style>
